﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.AnalysisServices.AdomdClient;

namespace MDX_Studio_v2
{
	public partial class MainForm : Form
	{
		// Settings
		internal Context _Context = new Context();
		internal Context Context
		{
			get { return _Context; }
			set { _Context = value; }
		}

		// Dockable windows
		private List<QueryEditor> queryEditors = new List<QueryEditor>();	// queryEditors

		private int queryEditorsCount = 0, activeQueryEditor = 0;

		private ResultsWindow _resultWindow = new ResultsWindow();
		private PerfmonWindow _perfmonWindow;
		private CubeTreeWindow _cubeTree;
		private ParametersWindow _parametersWindow;

		/// <summary>
		/// Form constructor
		/// </summary>
		public MainForm()
		{
			InitializeComponent();

			InitializeSettings();	// Initialize Settings

			// Initialize Parameters window
			_parametersWindow = new ParametersWindow();
			_parametersWindow.Show(dockPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockRight);
			_parametersWindow.Context = _Context;

			// Initialize a new Query Editor
			this.SpawnQueryEditor();

			// Initialize Perfmon window
			_perfmonWindow = new PerfmonWindow();
			_perfmonWindow.Show(dockPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockLeft);

			// Initialize Cube Tree
			_cubeTree = new CubeTreeWindow();
			_cubeTree.Show(dockPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockLeft);
			_cubeTree.Context = _Context;

			
		}

		// Spawn new Query(editor)
		private void SpawnQueryEditor(string filePath=null)
		{
			QueryEditor tmp = new QueryEditor();
			QueryEditorInfo tmp2 = new QueryEditorInfo(queryEditorsCount, filePath);
			//if(_Context.DebugMode) tmp.Query = "SELECT\r\n{\r\n\t[Measures].[Billable Hours],\r\n\t[Measures].[Fees Billed]\r\n}\r\nON 0,\r\n\r\n[Office].[Office].MEMBERS\r\n* [Department].[Department].MEMBERS\r\nON 1\r\n\r\nFROM\r\n\tRevenue";
			if (_Context.DebugMode) tmp.Query = "WITH\r\nSET [Core Measures] AS\r\n	{\r\n		[Measures].[Billable Fees],\r\n		[Measures].[Fees Billed],\r\n		[Measures].[Fees Collected],\r\n		NULL\r\n	}\r\n\r\nSELECT \r\n	[Core Measures] +\r\n	{\r\n		[Measures].[WIP Fees],\r\n		[Measures].[AR Fees],\r\n\r\n		[Measures].[Billable Fees % Value],\r\n		[Measures].[Billable Fees % Status],\r\n		[Measures].[Fees Billing Realization % Value],\r\n		[Measures].[Fees Billing Realization % Status],\r\n		[Measures].[Fees Collection Realization % Value],\r\n		[Measures].[Fees Collection Realization % Status],\r\n		NULL\r\n	}\r\n	ON 0,\r\n    \r\n	NONEMPTY([Matter].[Client].MEMBERS	* [Matter].[Matter].[Matter].MEMBERS, [Core Measures])\r\n	DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_KEY\r\n	ON 1\r\n\r\nFROM\r\n	Revenue\r\nWHERE\r\n(\r\n	// Applies to all:\r\n//	[Period].[Period].&[201004],	//@PeriodId=201004\r\n	STRTOMEMBER(\"[Period].[Period].&[\" + @PeriodId + \"]\"),\r\n	[Period Calculation].[Period Calculation].&[NONE],\r\n	[Scenario].[Scenario].[Zero Filter]\r\n);";
			queryEditors.Add(tmp);
			queryEditors[queryEditorsCount].Info = tmp2;
			queryEditors[queryEditorsCount].Show(dockPanel);
			queryEditors[queryEditorsCount].SetParameterWindow(_parametersWindow);
			queryEditorsCount++;

			_resultWindow.Show(dockPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockBottom);
		}

		/// <summary>
		/// Event fired when the "Open Cube Script on Load" option is toggled
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuOption_CubeScriptOnLoad_CheckedChanged(object sender, EventArgs e)
		{
			if (menuOption_CubeScriptOnLoad.CheckState == CheckState.Checked)
			{
				menuOption_CubeScriptBackground.Enabled = true;
				//TODO: determine from saved settings if should be checked
			}
		}

		/// <summary>
		/// Event fired when the Main Form is loaded
		/// Opens the ConnectionWindow with current settings
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void MainForm_Shown(object sender, EventArgs e)
		{
			ShowConnectionWindow();
		}

		/// <summary>
		/// Function to instantiate the ConnectionWindow and events
		/// </summary>
		private void ShowConnectionWindow()
		{
			ConnectionWindow cw = new ConnectionWindow();
			cw.Context = _Context;
			cw.ContextUpdated += new ConnectionWindow.ContextUpdatedHandler(ConnectionWindow_ConnectButtonClicked);
			cw.ShowDialog(this);
		}

		/// <summary>
		/// Initialze the saved settings, or instatiate defaults
		/// </summary>
		private void InitializeSettings()
		{
			// Set up Connection
			// TODO: establish rest of the connection
			SSASConnection conn = new SSASConnection();
			if (_Context.DebugMode)
			{

				conn.ServerName = ".\\V2012";
				conn.Catalog = "BI";
				conn.Cube = "Revenue";

			}
			// TODO: else if load from settings

			_Context.Connection = conn;
			_Context.MainForm = this;

			// TODO: set colors
			// TODO: load recently opened
		}

		/// <summary>
		/// SettingsUpdated in ConnectionWindow handler
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ConnectionWindow_ConnectButtonClicked(object sender, Context e)
		{
			// Save settings within this form
			this.Context = e;
			this.Context.Connection.ConnectToServer();

			if (_Context.DebugMode) Console.WriteLine(_Context.Connection.ToString());	// Debug

			// Update dropdowns
			toolstrip_drop_Catalog.Items.Clear();
			toolstrip_drop_Cube.Items.Clear();
			Microsoft.AnalysisServices.DatabaseCollection catalogs = _Context.Connection.ListCatalogs();
			if (catalogs != null)
			{
				int i = 0, j = 0;
				foreach (Microsoft.AnalysisServices.Database catalog in catalogs)
				{
					toolstrip_drop_Catalog.Items.Add(catalog.Name);
					if (catalog.Name == _Context.Connection.Catalog)
						j = i;
					i++;
				}
				toolstrip_drop_Catalog.SelectedIndex = j;

				Microsoft.AnalysisServices.CubeCollection cubes = _Context.Connection.ListCubes(_Context.Connection.Catalog);
				if (cubes != null)
				{
					i = j = 0;
					foreach (Microsoft.AnalysisServices.Cube cube in cubes)
					{
						toolstrip_drop_Cube.Items.Add(cube.Name);
						if (cube.Name == _Context.Connection.Cube)
							j = i;
							i++;
					}
					toolstrip_drop_Cube.SelectedIndex = j;
				}
			}
		}

		/// <summary>
		/// Event fired on the Connect Button clicked
		/// Launches the ConnectionWindow
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void toolstrip_Connect_Click(object sender, EventArgs e)
		{
			ShowConnectionWindow();
		}

		/// <summary>
		/// Event fired on the Exit menu item click
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuItem_Exit_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void PropagateContext()
		{
			if (_perfmonWindow != null) _perfmonWindow.Context = _Context;
			//if (_resultWindow != null) _resultWindow.Context = _Context;
			if (_parametersWindow != null) _parametersWindow.Context = _Context;
		}

		/// <summary>
		/// Event fired on the New Query Button pressed
		/// Launches a new Query
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void toolstrip_NewQuery_Click(object sender, EventArgs e)
		{
			// TODO: Add support for multiple queries
			this.SpawnQueryEditor();
		}

		/// <summary>
		/// Event fired when the Exit menu item is hovered over
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuItem_Exit_MouseHover(object sender, EventArgs e)
		{
			menuItem_Exit.Image = Properties.Resources.door_out;	// Change the icon to an open door
		}

		/// <summary>
		/// Event fired when the Exit menu item is un-hovered/mouse leave
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuItem_Exit_MouseLeave(object sender, EventArgs e)
		{
			menuItem_Exit.Image = Properties.Resources.door;		// Change the icon to a closed door (default)
		}



		/// <summary>
		/// Event fired when ShowPerfmon check is changed
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuOption_ShowPerfmon_CheckStateChanged(object sender, EventArgs e)
		{
			// TODO
		}

		/// <summary>
		/// Event fired on Main Form Closing
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			foreach (QueryEditor q in queryEditors)
			{
				// Find unsaved changed
				if (q != null && q.Info.UnsavedChanges == true)
				{
					// TODO: Save unsaved changes to ...?
					Console.WriteLine("Unsaved Changes {0}", q.Info.Title);
				}
			}
		}

		/// <summary>
		/// Event fired when the Execute button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void toolstrip_Execute_Click(object sender, EventArgs e)
		{
			//this.ExecuteQuery();
			DoIt();
		}

		private void menuItem_ClearCache_Click(object sender, EventArgs e)
		{
			this.ClearCache();
		}

		private void menuItem_ClearCacheExecute_Click(object sender, EventArgs e)
		{
			this.ClearCache();
			DoIt();
		}

		private void toolstrip_CancelExecution_Click(object sender, EventArgs e)
		{
			if (_worker.IsBusy && _worker.WorkerSupportsCancellation)
				_worker.CancelAsync();
		}
	}
}
